﻿using System.Configuration;

namespace WpfApp1;

public static class ConfigHelper
{
    /// <summary>
    /// 获取AppSettings配置值
    /// </summary>
    public static string GetAppSetting(string key)
    {
        return ConfigurationManager.AppSettings[key];
    }

    /// <summary>
    /// 设置/更新AppSettings配置值（保存修改）
    /// </summary>
    public static void SetAppSetting(string key, string value)
    {
        var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        var settings = configFile.AppSettings.Settings;

        if (settings[key] == null)
        {
            settings.Add(key, value);
        }
        else
        {
            settings[key].Value = value;
        }

        configFile.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
    }

    /// <summary>
    /// 获取连接字符串
    /// </summary>
    public static string GetConnectionString(string name)
    {
        return ConfigurationManager.ConnectionStrings[name]?.ConnectionString;
    }

    /// <summary>
    /// 设置/更新连接字符串（保存修改）
    /// </summary>
    public static void SetConnectionString(string name, string connectionString, string providerName = "System.Data.SqlClient")
    {
        var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        var settings = configFile.ConnectionStrings.ConnectionStrings;

        if (settings[name] == null)
        {
            settings.Add(new ConnectionStringSettings(name, connectionString, providerName));
        }
        else
        {
            settings[name].ConnectionString = connectionString;
            settings[name].ProviderName = providerName;
        }

        configFile.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection(configFile.ConnectionStrings.SectionInformation.Name);
    }
}